package com.system.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.lg.base.LoadProperties;
import com.lg.base.RequestLog;
import com.system.anno.RequestLogInterface;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 统一日志处理切面
 * 
 * @Package: com.system.interceptor
 * @ClassName: WebLogAspect.java
 * @Description:统一日志处理切面
 * 
 * @author kaifa008
 * @date 2022年6月26日 上午12:13:44
 * @Copyright: 2022 Copyright (c) 2018 LgSteel
 */
@Slf4j
@Aspect
@Component
@Order(1)
public class WebLogAspect {

	// private static final String RequestLogQueueKey = "request.log.queue";
	
	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;
	
	@Pointcut("execution(public * com.lg.controller..*.*(..))")
	public void webLog() {
	}

	@Around("webLog()")
	public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
		long startTime = System.currentTimeMillis();
		// 获取当前请求对象
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		RequestLog requestLog = new RequestLog();
		requestLog.setStartTime(String.valueOf(startTime));
		requestLog.setMark(0);
		Object result = null;
		try {
			result = joinPoint.proceed();
			requestLog.setData(result);
			requestLog.setSuccessFlag(0);
			// 判断该方法是否要记录
			Signature signature = joinPoint.getSignature();
			MethodSignature methodSignature = (MethodSignature) signature;
			Method targetMethod = methodSignature.getMethod();
			if (targetMethod.isAnnotationPresent(RequestLogInterface.class)) {
				RequestLogInterface requestLogInterface = targetMethod.getAnnotation(RequestLogInterface.class);
				requestLog.setMark(requestLogInterface.returnDateFlag());
				createRequestLogMQForSend(requestLog, request, joinPoint);
			}
		} catch (Exception e) {
			requestLog.setData(e);
			requestLog.setSuccessFlag(1);
			createRequestLogMQForSend(requestLog, request, joinPoint);
			log.error("WebLogAspect出错了啊啊啊啊啊啊！");
			throw e;
		}
		return result;
	}
	
	public void createRequestLogMQForSend(RequestLog requestLog, HttpServletRequest request, ProceedingJoinPoint joinPoint) {
		try {
			HttpSession session = request.getSession(true);
			Object user = session.getAttribute("user");
			if (user == null) {
				return;
			}
			// 获取参数数组
			Map<String, Object> parameterMap = getParameterMap(request);
			long endTime = System.currentTimeMillis();
			String urlStr = null;
			if (requestLog.getSuccessFlag() == 0) {
				try {
					urlStr = request.getRequestURL().toString();
				} catch (Exception e) {
				}
			}
			String userAgent = request.getHeader("User-Agent");
			if (!StringUtils.isNotEmpty(userAgent)) {
				requestLog.setUserAgent("");
			} else {
				requestLog.setUserAgent(userAgent.toLowerCase());
			}
			// 系统的用户信息取值
			// requestLog.setUserID(user.getUserID());
			// requestLog.setUserName(user.getUserName());
			if (requestLog.getSuccessFlag() == 0) {
				if (requestLog.getMark() == 0) {
					Object result = requestLog.getData();
					String finalResult = "";
					if (result != null) {
						if (result instanceof String) {
							finalResult = (String) result;
						} else {
							finalResult = JSONUtil.parse(result).toString();
						}
					}
					requestLog.setResult(finalResult);
				}
			} else {
				Exception exception = (Exception) requestLog.getData();
				String exceptionOut = ExceptionUtils.getFullStackTrace(exception);
				requestLog.setResult(exceptionOut);
			}
			requestLog.setData(null);
			if (StringUtils.isNotEmpty(urlStr)) {
				requestLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
			} else {
				requestLog.setBasePath(LoadProperties.SelfIP);
			}
			requestLog.setIp(request.getRemoteAddr());
			requestLog.setMethod(request.getMethod());
			requestLog.setParameterMap(parameterMap);
			requestLog.setSpendTime((int) (endTime - Long.valueOf(requestLog.getStartTime())));
			requestLog.setStartTime("");
			requestLog.setUri(request.getRequestURI());
			requestLog.setUrl(urlStr);
			// 加工系统
			requestLog.setSystemType(2);
			requestLog.setDescription("加工系统");
			requestLog.setDataSourceType(LoadProperties.isReal);
			if (LoadProperties.isReal == 1 && LoadProperties.windowOrLinux.equals("0")) {
	    		return;
	    	}
			asynSendRequestLog(requestLog);
		} catch (Exception e) {
			
		}
	}
	
	public void asynSendRequestLog(RequestLog requestLog) {
		taskExecutor.execute(() -> {
			try {
				System.out.println(JSONUtil.parse(requestLog).toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
	}
	
	/**
	 * 从request中获取参数
	 * @Title: getParameterMap   
	 * @Description: 从request中获取参数
	 * @param request
	 * @return
	 * @author: kaifa008
	 */
	public Map<String, Object> getParameterMap(HttpServletRequest request) {
		Map<String, Object> requestMap = new HashMap<>();
		Map<String, String[]> map = request.getParameterMap();
		Iterator<?> iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<?, ?> element = (Entry<?, ?>) iter.next();
			String strKey = element.getKey().toString();
			String[] value = (String[]) element.getValue();
			String values = "";
			if (value.length > 0) {
				for (int i = 0; i < value.length; i++) {
					values = values + value[i].toString() + ",";
				}
				values = values.substring(0, values.length() - 1);
			}
			requestMap.put(strKey, values);
		}
		return requestMap;
	}

}